package com.horoscope.astrology.zodiac.signs.free.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import com.google.android.gms.common.util.Base64Utils
import com.google.gson.Gson
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.bean.ConfigResultBean
import com.horoscope.astrology.zodiac.signs.free.network.NetworkEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.utils.*
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ADConfig
import kotlinx.android.synthetic.main.activity_splash.*
import java.lang.ref.WeakReference


class SplashActivity : BaseActivity() {

    private var bean: ConfigResultBean.ConfigResultBeanData? = null
    private val mHandler = SplashHandler(this@SplashActivity)

    companion object {
        /** 将活动置于沉浸式模式所需的所有标志的组合 */
        const val FLAGS_FULLSCREEN =
            View.SYSTEM_UI_FLAG_LOW_PROFILE or
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        const val TYPE_FROM = "type"
        const val PUSH_PM = "Push_Article"
        const val PUSH_AM = "Push_Horoscope"
        const val PUSH_QUIZ = "Push_Quiz"
        const val SHOW_TIME_MIN = 3500L // 最小显示时间
        fun generateIntent(context: Context): Intent {
            return Intent(context, SplashActivity::class.java)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        try {
            val bundle: Bundle? = intent.extras
            if (bundle == null) {
                if (!this.isTaskRoot) {
                    if (isTask()) return
                }
            } else {
                if (!this.isTaskRoot && !bundle.containsKey("type")) { // 判断当前activity是不是所在任务栈的根
                    if (isTask()) return
                }
            }
            // 初始化广告配置
            requestAdConfig()
            otherFlurry()
            asyncInit()
        } catch (e: Exception) {
            otherFlurry()
            asyncInit()
            Log.e("wsTest-Splash", e.toString())
        }
    }

    private fun isTask(): Boolean {
        val intent = intent
        if (intent != null) {
            val action = intent.action
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action) {
                finish()
                return true
            }
        }
        return false
    }

    private fun asyncInit() {
        val thread = object : Thread() {
            override fun run() {
                super.run()
                val message = Message.obtain()
                message.arg1 = 2
                val bundle = Bundle()
                bundle.putLong("time", System.currentTimeMillis())
                message.data = bundle
                mHandler.sendMessage(message)
            }
        }
        thread.start()
    }

    private fun otherFlurry() {

        val aHours: Long = 24 * 3600 * 1000
        val cureentTimes: Long = System.currentTimeMillis()
        val installTime: Long = AppSettingManager.readLong("installTime", 0L)

        if (installTime == 0.toLong()) { //首次安装
            AppSettingManager.saveLong(SysUtils.zeroClockOnTheDay(), "installTime")

        } else { // 其他时间打点

            // 时间戳差值[当前时间-安装0点时间]
            val timeDiff = cureentTimes - installTime
            when (timeDiff / aHours) {
                1L -> {
                    if (AppSettingManager.recordFirstTime("second")) {
                        FlurryEventUtil.putDataToEvent(EventType.TYPE_SECOND_RETURN, null, null)
                        FlurryEventUtil.logUnlockAchievementEvent(EventType.TYPE_SECOND_RETURN)
                    }
                }
                4L -> {
                    if (AppSettingManager.recordFirstTime("five")) {
                        FlurryEventUtil.putDataToEvent(EventType.TYPE_FIVE_RETURN, null, null)
                        FlurryEventUtil.logUnlockAchievementEvent(EventType.TYPE_FIVE_RETURN)
                    }
                }
                6L -> {
                    if (AppSettingManager.recordFirstTime("seven")) {
                        FlurryEventUtil.putDataToEvent(EventType.TYPE_SEVEN_RETURN, null, null)
                        FlurryEventUtil.logUnlockAchievementEvent(EventType.TYPE_SEVEN_RETURN)
                    }
                }
                14L -> {
                    if (AppSettingManager.recordFirstTime("fifteen")) {
                        FlurryEventUtil.putDataToEvent(EventType.TYPE_FIFTEEN_RETURN, null, null)
                        FlurryEventUtil.logUnlockAchievementEvent(EventType.TYPE_FIFTEEN_RETURN)
                    }
                }
                29L -> {
                    if (AppSettingManager.recordFirstTime("thirty")) {
                        FlurryEventUtil.putDataToEvent(EventType.TYPE_THIRTY_RETURN, null, null)
                        FlurryEventUtil.logUnlockAchievementEvent(EventType.TYPE_THIRTY_RETURN)
                    }
                }
            }
        }

        if (intent?.getStringExtra(TYPE_FROM).orEmpty().isEmpty()) {
            // 程序打开的来源（launch启动）
            FlurryEventUtil.putDataToEvent(EventType.TYPE_APP_OPEND, "type", "icon")
        }

    }

    class SplashHandler(activity: SplashActivity) : Handler() {
        private val mActivity: WeakReference<SplashActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if (mActivity.get() == null) return

            val activity = mActivity.get()
            when (msg?.arg1) {
                2 -> {// 初始化的时间超过了3.5秒则直接跳转
                    val mStartTime = msg.data.getLong("time")
                    val dif = System.currentTimeMillis() - mStartTime
                    if (dif < SHOW_TIME_MIN) {
                        activity?.let { next(SHOW_TIME_MIN, it) }
                    } else {
                        activity?.let { next(0, it) }
                    }
                }
            }
        }

        private fun next(time: Long, activity: SplashActivity) {
            this@SplashHandler.postDelayed({
                activity.nextM()
                activity.finish()
            }, time)
        }
    }

    /**
     * 主要判断打开的方式
     * 1、新用户 -> UserBean
     * 2、icon正常启动
     * 3、Push -> 前台 Intent
     *        ->  后台 隐式启动 Bundle
     */
    private fun nextM() {
        val bundle: Bundle? = intent.extras
        if (!AppSettingManager.contains("user_info")) { // 新用户
            startActivity(Intent(this@SplashActivity, StartActivity::class.java))
        } else if (bundle != null && bundle.containsKey("type")) { // 接到Push启动app(debug状态是没有Bundle的，正式点击图标有bundle无数据)
            selectorActivity(bundle)
        } else if (bundle != null && bundle.containsKey("Alarm")) {
            fromAlarm()
        } else { // 正常启动
            startActivity(Intent(this@SplashActivity, MainActivity::class.java))
        }
    }

    // 闹钟（NameCompatibility,RelationCompatibility,InputProfile）
    private fun fromAlarm() {
        val type = intent.getIntExtra("alarm_type", 0)
        val workName = intent.getStringExtra("workName")

        NotificationUtil.cancelNotification(type)

        val mainIntent = Intent(this, MainActivity::class.java)
        mainIntent.putExtra("page", 1)

        val otherIntent = Intent(
            this, when (type) {
                1011 -> NameCompatibilityActivity::class.java
                1012 -> RelationCompatibilityActivity::class.java
                1013 -> InputProfileActivity::class.java
                else -> null
            }
        )
        otherIntent.putExtra("Alarm", true)
        otherIntent.putExtra("workName", workName)
        otherIntent.putExtra("alarm_type", type)

        startActivities(arrayOf(mainIntent, otherIntent))
    }

    // 推送（Article、Quiz）
    private fun selectorActivity(bundle: Bundle) {
        try {
            when (bundle.getString(TYPE_FROM)) {
                "1" -> {
                    FlurryEventUtil.putDataToEvent(EventType.TYPE_APP_OPEND, "type", PUSH_AM)
                    startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                }
                "2" -> {
                    pushArticleOrQuiz(bundle)
                }
                "3" -> {
                    pushArticleOrQuiz(bundle)
                }
                else -> startActivity(Intent(this@SplashActivity, MainActivity::class.java))
            }
        } catch (e: Exception) {
            e.printStackTrace()
            startActivity(Intent(this@SplashActivity, MainActivity::class.java))
        }
    }

    private fun pushArticleOrQuiz(bundle: Bundle) {
        val pushIntent: Intent
        if (bundle.getString("type") == "2") {
            pushIntent = Intent(this@SplashActivity, ArticleDetailActivity::class.java)
            pushIntent.putExtra("article_url", bundle.getString("url"))
        } else {
            pushIntent = Intent(this@SplashActivity, QuizStartActivity::class.java)
            pushIntent.putExtra("quiz_url", bundle.getString("url"))
        }
        pushIntent.putExtra("push", true)
        startActivity(pushIntent)
    }

    // 请求广告配置
    private fun requestAdConfig() {
        val confitStr = AppSettingManager.readString("config_ad", "")
        bean = AppSettingManager.readAdConfigObject("config_ad") // 本地存的配置没有返回NULL
        /**
         * 首次登陆 网络获取配置并缓存
         * 非首次，先从本地拉取；再从网络获取并与本地比较进行存储
         * */
        if (bean == null) {
            getAdConfig(confitStr)
        } else {
            getLocalConfig(bean)
            NetworkEngine.getConfig(object : NetworkListener<ConfigResultBean>() {
                override fun onSuccess(t: ConfigResultBean) {
                    val (temp, configBean) = buildAdConfig(t)
                    if (confitStr.isNotEmpty()) { // 有本地配置
                        if (confitStr != String(temp)) { // 本地配置与服务器不同
                            // 拉取最新配置储存
                            AppSettingManager.saveObject(configBean, "config_ad")
                        }
                    } else {
                        AppSettingManager.saveObject(configBean, "config_ad")
                    }
                }
            })
        }
    }

    private fun getAdConfig(confitStr: String) {
        NetworkEngine.getConfig(object : NetworkListener<ConfigResultBean>() {

            override fun onSuccess(t: ConfigResultBean) {
                val (temp, configBean) = buildAdConfig(t)

                if (confitStr.isNotEmpty()) { // 有本地配置
                    if (confitStr != String(temp)) { // 本地配置与服务器不同
                        // 拉取最新配置储存
                        initAndSaveAdConfig(configBean)
                    } else {
                        getLocalConfig(configBean)
                    }
                } else {
                    initAndSaveAdConfig(configBean)
                }
            }

            override fun onFailed(t: ConfigResultBean) {
                super.onFailed(t)
                getLocalConfig(bean)
            }

            override fun onError(e: String?) {
                super.onError(e)
                getLocalConfig(bean)
            }
        })
    }

    private fun buildAdConfig(t: ConfigResultBean): Pair<ByteArray, ConfigResultBean.ConfigResultBeanData> {
        val byteArray = Base64Utils.decode(t.data)
        val resArray =
            AesUtils.decrypt(byteArray, getString(R.string.Ad_config_Bsee64_pwd))
        var j = 0
        for (element in resArray) {
            if (element != 0.toByte()) {
                j++
            }
        }
        val temp = resArray.copyOf(j)
        val configBean = Gson().fromJson(
            String(temp),
            ConfigResultBean.ConfigResultBeanData::class.java
        )
        return Pair(temp, configBean)
    }

    private fun initAndSaveAdConfig(configBean: ConfigResultBean.ConfigResultBeanData) {
        // 初始化广告配置（包括AppId、三种类型广告的ArrayList）
        ADConfig.mInstance.init(configBean, this)
        // sp里将bean转成Json字符串做缓存
        AppSettingManager.saveObject(configBean, "config_ad")
    }

    // 接口请求错误，从本地拉取缓存的配置
    private fun getLocalConfig(bean: ConfigResultBean.ConfigResultBeanData?) {
        if (bean != null) {
            ADConfig.mInstance.init(bean, this)
        } else {
            val resultBean =
                Gson().fromJson(
                    ConstellationUtil.getAdConfig(),
                    ConfigResultBean.ConfigResultBeanData::class.java
                )
            resultBean?.let {
                initAndSaveAdConfig(resultBean)
            }
        }
    }

    override fun dismissStatusBar(): Boolean {
        return true
    }

    override fun onResume() {
        super.onResume()
        container.postDelayed({
            container.systemUiVisibility = FLAGS_FULLSCREEN
        }, 500L)
    }

    override fun onDestroy() {
        mHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

}